package com.leaves.common.interceptor;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.leaves.common.constant.RedisConstant;
import com.leaves.common.util.IpUtil;
import com.leaves.exception.MessageCenterException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2022年08月09日  16时15分40秒
 * @Description: 在指定时间内请求次数限制
 */
@Component
public class AccessLimitIntercept implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AccessLimitIntercept.class);

    @Value("${IpLimit.count}")
    private int count;
    @Value("${IpLimit.time}")
    private int time;
    @Value("${token.renewalTime}")
    private long tokenRenewalTime;

    /**
     * 接口调用前检查对方ip是否频繁调用接口
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TOKEN自动续签
        StpUtil.renewTimeout(tokenRenewalTime);
        // handler是否为 HandleMethod 实例
        if (handler instanceof HandlerMethod) {
            //可以过滤掉无需限流的接口或者自定义注解进行限流


            // 拼接redis key = IP + Api限流
            String key = RedisConstant.LIMIT + IpUtil.getIpAddress(request) + request.getRequestURI();
            // 获取redis的value
            Integer maxTimes = null;
            String value = SaManager.getSaTokenDao().get(key);
            if (ObjectUtil.isNotNull(value)) {
                maxTimes = Integer.valueOf(value);
            }
            if (maxTimes == null) {
                maxTimes = 1;
                logger.info("当前请求次数：{}", maxTimes);
                // 如果redis中没有该ip对应的时间则表示第一次调用，保存key到redis
                SaManager.getSaTokenDao().set(key, String.valueOf(maxTimes), time);
            } else if (maxTimes < count) {
                maxTimes = maxTimes + 1;
                logger.info("当前请求次数：{}", maxTimes);
                // 如果redis中的时间比注解上的时间小则表示可以允许访问,这是修改redis的value时间
                SaManager.getSaTokenDao().set(key, String.valueOf(maxTimes), time);
            } else {
                // 请求过于频繁
                logger.error("API请求限流拦截启动,{} 请求过于频繁", key);
//                throw new MessageCenterException("Requests are too frequent, please try again later.");
                throw new MessageCenterException("请求过于频繁，请稍后再试");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
